require(['gaodeMap', 'highcharts', 'zTreeCheckbox', 'select2', 'canGrid', 'homePageTools'], function () {
    //===================================变量
	//TODO
    var dateType = '02', 															//日期类型，默认昨天
    	lineId,																		//线路id
        lineName,																	//线路名称
        setting,																	//线路树参数设置
        //TODO
//        dateString = '2016-01-25',														
        dateString = ((new Date()).dateAdd('d',-1)).format(),						//日期字符串
        dateAr = [],																//日期数组
        $lineTree = $("#lineTree"),													//左侧树
        $stnLineCharts = $("#stnLineCharts"),										//上行线路站点图
        $downStnLineCharts = $("#downStnLineCharts"),								//下行线路站点图
        $vehicleTypeTab = $("#vehicleTypeTab"),										//车辆故障排名表
        $unsafeDrvTab = $("#unsafeDrvTab"),											//不安全行为排名表
        stationMarkers = [],														//车站Marker集合
        unsafeAr,																	//不安全行为信息位置集合
        drvSctBhvType,																//不安全行为类型
        infoWindow,																	//地图上的消息气泡
        map,																		//地图
        toolBar,																	//尺寸条
        upInfoWin,																	//上行消息框数组
        upPosition,																	//上行消息标记坐标
        upCircleAreaAr = [],														//上行圆形区域数组
        downInfoWin,																//下行消息框数组
        downPosition,																//下行消息标记坐标
        downCircleAreaAr = [],														//下行圆形区域数组
        tmpUpStopNameAr = [],														//备份上行站点名称数组
        tmpDownStopNameAr = [];														//备份上行站点名称数组
//    	var center;
    //=======================================函数
    //TODO
    /**
     * 初始化页面元素
     */
    function initElements(){
    	//初始化表单（仅从缓存中加载不安全行为类型）
        $('#selForm').initForm();
        //线路树参数设置
        setting = {
                view: {
                    showIcon: true,
                    selectedMulti: false
                },
                data: {
                    key: {
                        name: "name"
                    },
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentId",
                        rootPId: 0
                    }
                },
                callback: {
                    beforeClick: function (treeId, treeNode) {
                        return treeNode.type == 'LINE';
                    },
                    onClick: function (event, treeId, treeNode) {
                        if (treeNode.id == lineId) {
                            return;
                        }
                        var loadMask = $.createMask();
                        setLine(treeNode);
                        //加载各项
                        initPageData();
                        setTimeout(function () {
                            loadMask.remove();
                        }, 50);
                    }
                }
            };
        //初始化车辆故障排名表
        $vehicleTypeTab.canGrid({
            url: "/homeSafe/getVehicleFaultsRanking.htm",
            height:250,
            colModel: [
                {name: "ranking", label: '排名', width: '15%', align:'center'},
                {name: "carLic", label: '车牌号', width: '20%', align:'center'},
                {name: "totalFaults", label: '故障总数', width: '15%', align:'center'},
                {name: "seriousFaults", label: '重大故障数', width: '15%', align:'center'},
                {name: "commonFaults", label: '一般故障数', width: '20%', align:'center'}
            ]
        });
        
        //初始化不安全行为排名表
        $unsafeDrvTab.canGrid({
            url: "/homeSafe/getUnsafeDriverRanking.htm",
            height:250,
            colModel: [
                {name: "ranking", label: '排名', width: '10%', align:'center'},
                {name: "driver", label: '驾驶员', width: '10%', align:'center'},
                {name: "totalBehaviors", label: '行为总数', width: '10%', align:'center'},
                {name: "bhvAcc", label: '超速', width: '10%', align:'center'},
                {name: "bhvDec", label: '急加', width: '10%', align:'center'},
                {name: "bhvCoast", label: '急减', width: '10%', align:'center'},
                {name: "bhvOpen", label: '异常关门', width: '10%', align:'center'},
                {name: "bhvClose", label: '异常开门', width: '10%', align:'center'},
                {name: "bhvOther", label: '其他', width: '10%', align:'center'}
            ]
        });
    }
    
    /**
     * 设置当前线路名称及ID
     */
    function setLine(item) {
        lineId = item.id;
        $("#showlineName").html("当前线路 : " + item.name);
        lineName = item.name;
    }

    /**
     * 初始化线路树
     */
    function initLineTree() {
        $.ajaxExt({
            async: false,
            url: "/baseOrgan/getLeftOrg4Line.htm"
        }).done(function (result) {
            if ($.isArray(result)) {
                $.each(result, function (index, item) {
                    if (item.type == 'LINE') {
                        setLine(item);
                        return false;
                    }
                });
                $lineTree.createTree(setting, result, {search: $('#lineSelected')}).expandAll(true);
            }
        });
    }
    
    /**
     * 获取日期类型对应日期数据
     */
    function getFullDate(){
    	//TODO
    	$.ajaxExt({
    		async : false,
    		url:"/homeTransit/getFullDate.htm",
    		data:{
    			"dateType":dateType,
    			"yesterday":((new Date()).dateAdd('d',-1)).format()
//    			"yesterday":'2016-01-25'
    		}
    	}).done(function(data){
    		if(data && data.length > 0){
    			for(var i =0;i<data.length;i++){
    				dateAr.push(data[i].trendDate);
    			}
    			if(dateType=='02'){
    				//TODO
    	    		dateString = ((new Date()).dateAdd('d',-1)).format();
//    	    		dateString = '2016-01-25';
    	    	}else if(dateType == '03'){
    				dateString = data[0].trendDate+"-"+data[data.length-1].trendDate;
    			}else if(dateType == '04' || dateType == '05'){
    				dateString = data[0].trendDate.substring(0, 7)+"月";
    			}else if(dateType == '07' || dateType == '06'){
    				dateString = data[0].trendDate.substring(0, 4)+"年";
    			}
    		}
    	});
    }
    
	/**
	 * 加载指标
	 */
    function loadSafeIndex () {
        $.ajaxExt({
            url: "/homeSafe/getSafeIndex.htm",
            data: {"dateType": dateType, "lineId": lineId, "className":"SafetyIndexVo", "funcType":"safeIndex"}
        }).done(function (data) {
            if (data && data.length > 0) {
                fillIndex($("#SERIOUS_FAULTS"), (data[0].seriousFaults ? data[0].seriousFaults : 0), (data[0].avgSerious ? data[0].avgSerious : 0), '次');
                fillIndex($("#COMMON_FAULTS"), (data[0].commonFaults ? data[0].commonFaults : 0), (data[0].avgCommon ? data[0].avgCommon : 0), '次');
                fillIndex($("#FAULT_CARS"), (data[0].faultCars ? data[0].faultCars : 0), (data[0].avgFaultCars ? data[0].avgFaultCars : 0), '辆');
                fillIndex($("#UBSAFE_BHV"), (data[0].ubsafeBhv ? data[0].ubsafeBhv : 0), (data[0].avgUbsafeBhv ? data[0].avgUbsafeBhv : 0), '次');
                fillIndex($("#UBSAFE_CARS"), (data[0].ubsafeCars ? data[0].ubsafeCars : 0), (data[0].avgUbsafeCars ? data[0].avgUbsafeCars : 0), '人');
            } else {
                fillIndex($("#SERIOUS_FAULTS"), 0, 0.0, '次');
                fillIndex($("#COMMON_FAULTS"), 0, 0.0, '次');
                fillIndex($("#FAULT_CARS"), 0, 0.0, '辆');
                fillIndex($("#UBSAFE_BHV"), 0, 0.0, '次');
                fillIndex($("#UBSAFE_CARS"), 0, 0.0, '人');
            }
        });
    }

    /**
     * 填充指标
     * @param obj 指标对应页面元素
     * @param idxVal 指标值
     * @param idxPer 环比值
     * @param unit 单位
     */
    fillIndex = function (obj, idxVal, idxPer) {
    	obj.html('');
        var html = "";
        if(!idxVal){
        	idxVal = 0;
        }
        if(!idxPer){
        	idxPer = '0.0';
        }
        if (idxPer > 0) {
            html = '<span class="icon-arrow-up" style="font-size: 13px;">' + idxPer + '%</span>';
        } else if (idxPer < 0) {
            html = '<span class="icon-arrow-up icon-arrow-down" style="font-size: 13px;">' + idxPer + '%</span>';
        }else{
        	html = '<span class="icon-arrow-up icon-arrow-unchanged" style="font-size: 13px;">' + idxPer + '%</span>';
        }
        obj.html(idxVal + html);
    };

    /**
     * 车辆故障排名详细信息
     */
    function loadVehicleFaultsRanking() {
        $vehicleTypeTab.canGrid('reload', {
            params: {"funcType": "vehicleFaultsRanking", 
            	"dateType": dateType, 
            	"lineId": lineId,
            	"className":"FaultsRankingVo"}
        });
        $vehicleTypeTab.html('');
    }

    /**
     * 安全首页趋势图(故障趋势,不安全行为趋势)
     * @param idxType 业务类型
     * @param obj 图表对应元素
     * @param title 标题
     */
    function loadHarmfulTendency(idxType, obj){
        $.ajaxExt({
            url: "/homeSafe/getHarmfulTendency.htm",
            data: {"funcType": "harmfulTendency", "dateType": dateType, "lineId": lineId, "className":"HarmfulTendencyVo", "idxType":idxType}
        }).done(function (data) {
        	var category = [],
        		series = [];
            var mainTitle = '',
            	subTitle = '线路：'+lineName+' 时间：'+dateString;
            //格式化数据
            formatSafetyTendencyData(data, dateType, category, series, dateAr);
            //生成趋势图
            createMultiTendencyChart(obj, mainTitle, subTitle, category, null, '次', series, dateType);
        });
    }

    /**
     * 故障和不安全行为类型排名
     * @param idxType 业务类型
     * @param obj 图表对应元素
     * @param name 标题
     */
    function harmfulTypeRanking(idxType, obj, name){
    	var dataAr = [];
        $.ajaxExt({
            url: "/homeSafe/getHarmfulTypeRanking.htm",
            data: {"funcType": "harmfulTypeRanking", "dateType": dateType, "lineId": lineId,"className":"HarmfulTypeRankingVo", "idxType":idxType}
        }).done(function (data) {
        	obj.empty();
        	if(data && data.length > 0 && data[0].tendencyName){
        		for (var i = 0; i < data.length; i++) {
        			dataAr.push([data[i].tendencyName, parseInt(data[i].tendencyCounts) || 0]);
        		}
        		obj.highcharts({
        			chart: {
        				height: 340
        			},
        			title: {text: ''},
        			credits: {
        				enabled: false
        			},
        			tooltip: {
        				formatter: function () {
        					return '<b>' + this.point.name + '</b>: ' + Highcharts.numberFormat(this.percentage, 1) + '% (' +
        					Highcharts.numberFormat(this.y, 0, ',') + ' 次)';
        				}
        			},
        			plotOptions: {
        				pie: {
        					allowPointSelect: true,
        					cursor: 'pointer',
        					dataLabels: {
        						enabled: true,
        						color: '#000000',
        						connectorColor: '#000000',
        						format: '<b>{point.name}</b>: {point.percentage:.1f}%,{point.y}次 '
        					}
        				}
        			},
        			series: [{
        				type: 'pie',
        				name: name,
        				data: dataAr
        			}]
        		});
        	}
        });
    }

    /**
     * 不安全司机排名
     */
    function loadUnsafeDriverRanking() {
        $unsafeDrvTab.canGrid('reload', {
            params: {"funcType": "unsafeDriverRanking", "dateType": dateType, "lineId": lineId, "className":"UnsafeBhvRankingVo"}
        });
    }


    /**
     * 查询所选线路所在城市
     */
    function loadLineCity() {
        $.ajaxExt({
            url: "/homeSafe/getLoadLineCity.htm",
            data: {"funcType": "loadLineCity", "lineId": lineId, "className":"MapBaseDataVo"}
        }).done(function (data) {
        	var city = '', province = '';
            if (data && data.length > 0) {
            	city = data[0].city;
            	province = data[0].province;
            }
            lineSearch(city, lineName, province);
        });
    }

    /**
     * 公交线路查询
     * @param city 城市名称
     * @param lineName 线路名称
     */
    function lineSearch(city, lineName, province) {
    	var loct = city;
    	if(province == '北京'||province == '上海'||
         province == '天津'||province == '重庆'){
    		loct = province;
        }
    	/*
         * 1. 首先调用公交路线查询服务(lineSearch)
         * 2. 根据返回结果解析，输出解析结果(lineSearch_Callback)
         * 3. 在地图上绘制公交线路()
         */
        var linesearch = new AMap.LineSearch({
            pageIndex: 1,
            city: loct,
            pageSize: 2,
            extensions: 'all'
        });
        if(!linesearch){
        	map.setCity(city);
        }
        linesearch.search(lineName, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                lineSearch_Callback(result);
                var lineArr = result.lineInfo;
                var stops = lineArr[0].via_stops;
                var stationsLen = lineArr[0].via_stops.length;
                for (var i = 0; i < stationsLen; i++) {
                    stationMarkers.push(new AMap.Marker({
                        map: map,
                        position: lineArr[0].via_stops[i].location,
                        offset: new AMap.Pixel(-3, -3),
                        icon: $.getProjectName() + "/content/images/way_btn2.png",
                        title: lineArr[0].via_stops[i].name,
                        zIndex: 13
                    }));
                    //TODO
                }
                
                for(var i = 0; i < lineArr[0].via_stops.length; i++){
                	tmpUpStopNameAr.push(lineArr[0].via_stops[i].name);
                }
                if(lineArr.length > 1){
                	for(var i = 0; i < lineArr[1].via_stops.length; i++){
                		tmpDownStopNameAr.push(lineArr[1].via_stops[i].name);
                	}
                }else{
                	for(var i = lineArr[0].via_stops.length -1 ; i >= 0; i--){
                		tmpDownStopNameAr.push(lineArr[0].via_stops[i].name);
                	}
                }
                //map.setCity(city);
            }
            else{
            	map.setCity(city);
            }
        });
    }
    
	/**
	 * 公交路线查询服务返回数据解析概况
	 * @param data 线路数据集合（包括绘制线路的基点经纬度数据）
	 */
    function lineSearch_Callback(data) {
        var lineArr = data.lineInfo;
        var lineNum = data.lineInfo.length;
        if (lineNum == 0) {
        } else if(lineNum == 1){
        	for (var i = 0; i < lineNum; i++) {
                var pathArr = lineArr[i].path;
                var stops = lineArr[i].via_stops;
                var startPot = stops[0].location;
                var endPot = stops[stops.length - 1].location;
                if (i == 0)
                    drawbusLine(startPot, endPot, pathArr);
            }
        } else {
            for (var i = 0; i < lineNum-1; i++) {
                var pathArr = lineArr[i].path;
                var stops = lineArr[i].via_stops;
                var startPot = stops[0].location;
                var endPot = stops[stops.length - 1].location;
                if (i == 0)
                    drawbusLine(startPot, endPot, pathArr);
            }
        }
    }
    
	/**
	 * 绘制路线
	 * @param startPot 开始站点位置信息
	 * @param endPot 结束站点位置信息
	 * @param BusArr 公交线路基点经纬度集合
	 */
    function drawbusLine(startPot, endPot, BusArr) {
    	markMostFaultsStn();
        //绘制起点，终点
        new AMap.Marker({
            map: map,
            position: [startPot.lng, startPot.lat], //基点位置
            icon: $.getProjectName() + "/content/images/start_flag.png",
            zIndex: 10
        });
        new AMap.Marker({
            map: map,
            position: [endPot.lng, endPot.lat], //基点位置
            icon: $.getProjectName() + "/content/images/end_flag.png",
            zIndex: 10
        });
        //绘制乘车的路线
        busPolyline = new AMap.Polyline({
            map: map,
            path: BusArr,
            strokeColor: "#09f",//线颜色
            strokeOpacity: 0.8,//线透明度
            strokeWeight: 6//线宽
        });
        map.setFitView();
        createLineStnChart();
        
        createTimeUnsafeCharts();
        //绘制
    }

    /**
     * 标注发生故障次数前五站点
     */
    function markMostFaultsStn() {
        var drvSctBhvType = $("#drvSctBhvType").val();
        $.ajaxExt({
            async: false,
            url: "/homeSafe/getUnsafeMap.htm",
            data: {"funcType": "unsafeMap", "dateType": dateType, "drvSctBhvType": drvSctBhvType, "lineId": lineId, "className":"UnsafeMapVo"}
        }).done(function (data) {
            unsafeAr = data;
            if (data && data.length > 0) {
            	var tmpCount = 0, //存放次数最多的故障数，用于地图默认标注发生次数最多故障信息
            	upDown = '0';	//上下行标记，默认上行
                for (i = 0; i < data.length; i++) {
                    var lgt = data[i].prvsStnLgt;
                    var ltt = data[i].prvsStnLtt;
                    //标记不安全行为区域
                    if(lgt && ltt){
                    	var drvSctBhvCount = parseInt(data[i].drvSctBhvCount);
                    	if(!drvSctBhvCount){
                    		drvSctBhvCount = 0;
                    	}
                    	if(upDown != data[i].upDn){
                    		tmpCount = 0;
                    		upDown = data[i].upDn;
                    	}
                    	//标记不安全行为信息
                    	var infoWindow = new AMap.InfoWindow({
                    		content: '<p>不安全行为类型：' + data[i].codeDsc 
                    			+ '</p><p>不安全行为次数：' + drvSctBhvCount + '</p>'
                    	});
                    	//infoWindow.open(map, [lgt, ltt]);
                    	var circle = new AMap.Circle({
                    		center: new AMap.LngLat(lgt, ltt),// 圆心位置
                    		radius: 200, //半径
                    		strokeColor: "#F33", //线颜色
                    		strokeOpacity: 1, //线透明度
                    		strokeWeight: 3, //线粗细度
                    		fillColor: "#ee2200", //填充颜色
                    		fillOpacity: 0.35//填充透明度
                    	});
                    	circle.content = '<p>不安全行为类型：' + data[i].codeDsc + '</p><p>不安全行为次数：' + data[i].drvSctBhvCount + '</p>';
                    	circle.position = [lgt, ltt];
                    	circle.on('mouseover', markerClick);
                    	circle.emit('click', {target: circle});
                    	circle.setMap(map);
                    	if(data[i].upDn == '0'){
                    		if(drvSctBhvCount > tmpCount){
                    			tmpCount = drvSctBhvCount;
                    			upPosition = [lgt, ltt];
                        		upInfoWin = infoWindow;
                        	}
                    		upCircleAreaAr.push(circle);
                    	}else{
                    		if(drvSctBhvCount > tmpCount){
                    			tmpCount = drvSctBhvCount;
                    			downPosition = [lgt, ltt];
                        		downInfoWin = infoWindow;
                        	}
                    		downCircleAreaAr.push(circle);
                    	}
                    }
                }
                //隐藏下行气泡和圆形区域
                hideInfoWinAndCircle(downInfoWin, downCircleAreaAr);
                //显示上行
                showInfoWinAndCircle(upInfoWin, upPosition, upCircleAreaAr);
            }
        });
    }
    
    /**
     * 现实不安全行为消息和区域（只显示故障最高消息）
     */
    function showInfoWinAndCircle(infoWin, position, circleAr){
    	if(position && infoWin){
    		infoWin.open(map, position);
    	}
    	if(circleAr && circleAr.length > 0){
    		map.add(circleAr);
    	}
    }
    
    /**
     * 隐藏不安全行为消息和区域
     */
    function hideInfoWinAndCircle(infoWin, circleAr){
    	if(infoWin){
    		map.remove(infoWin);
    	}
    	if(circleAr && circleAr.length > 0){
    		map.remove(circleAr);
    	}
    }

    /**
     * 拼接线路站点
     * @param obj 线路站点图对应页面元素
     * @param stnAr 站点数据集合
     * @param updown 上下行
     */
    function initLineStationElements(obj, stnAr,  updown, div, sign) {
    	var length = stnAr.length;
    	var width = 120*(length-1)+60;
    	div.width(width);
        var html = '';
        if(sign == 1){
        	for (var i = 1; i <= stnAr.length; i++) {
        		html += '<li><div class="num">' + i + '</div>';
        		if(unsafeAr && unsafeAr.length > 0){
        			for (var s = 0; s < unsafeAr.length; s++) {
        				if (unsafeAr[s].prvsStnSn == i && updown == unsafeAr[s].upDn) {
        					html += '<div class="times">' + unsafeAr[s].drvSctBhvCount + '次</div>';
        				}
        			}
        		}
        		html += '<div class="radius"></div><div class="name">' + stnAr[i - 1].stnName + '</div><div class="line"></div></li>';
        	}
        }else{
        	for (var i = 1; i <= stnAr.length; i++) {
        		html += '<li><div class="num">' + i + '</div>';
        		if(unsafeAr && unsafeAr.length > 0){
        			for (var s = 0; s < unsafeAr.length; s++) {
        				if (unsafeAr[s].prvsStnSn == i && updown == unsafeAr[s].upDn) {
        					html += '<div class="times">' + unsafeAr[s].drvSctBhvCount + '次</div>';
        				}
        			}
        		}
        		html += '<div class="radius"></div><div class="name">' + stnAr[i - 1] + '</div><div class="line"></div></li>';
        	}
        }
        obj.append(html);
    }

    /**
     * 构建线路站点图
     */
    function createLineStnChart() {
    	$stnLineCharts.empty();//清空站点线路图
        $downStnLineCharts.empty();//清空站点线路图
        //var html = '', count = 0;
        //上行
        var strtusDate = '';
        $.ajaxExt({
            async: false,
            url: "/homeSafe/getLoadLineStnRelDate.htm",
            data: {"funcType": "loadLineStnRelDate", "lineId": lineId, "className":"MapBaseDataVo"}
        }).done(function (data) {
            if (data && data.length > 0) {
                strtusDate = data[0].strtusDate;
            }
        });
        $.ajaxExt({
            url: "/stnLineRel/getUpStnLineRelByLineId.htm",//请求后台url
            data: {"lineId": lineId, "strtusDate": strtusDate}
        }).done(function (data) {
        	if(data && data.length > 0){
        		initLineStationElements($stnLineCharts, data,  '0', $("#articleWidth"), 1);
        	}
        	else if(tmpUpStopNameAr && tmpUpStopNameAr.length > 0){
        		initLineStationElements($stnLineCharts, tmpUpStopNameAr,  '0', $("#articleWidth"), 0);
        	}
        });

        $.ajaxExt({
            url: "/stnLineRel/getDownStnLineRelByLineId.htm",//请求后台url
            data: {"lineId": lineId, "strtusDate": strtusDate}
        }).done(function (data) {
        	if(data && data.length > 0){
        		initLineStationElements($downStnLineCharts, data,  '1', $("#downArticleWidth"), 1);
        	}
        	else if(tmpDownStopNameAr && tmpDownStopNameAr.length > 0){
        		initLineStationElements($downStnLineCharts, tmpDownStopNameAr,  '1', $("#downArticleWidth"), 0);
        	}
        });
    }
    
    //TODO 构建时间故障图
    function createTimeUnsafeCharts(){
    	$("#timeLineCharts").empty();
    	$("#timeDownStnLineCharts").empty();
    	$.ajaxExt({
    		url: "/homeSafe/getUnsafeTimeData.htm",
    		data:{
    			"lineId":lineId,
    			"dateType":dateType,
    			"drvSctBhvType": $("#drvSctBhvType").val()
    		}
    	}).done(function(data){
//    		if(data && data.length > 0){
//    			combinUnsafeTimeCharts(data, 0, $("#timeLineCharts"));
//    			if(data.length > 24){
//    				combinUnsafeTimeCharts(data, 24, $("#timeDownStnLineCharts"));
//    			}else{
//    				combinUnsafeTimeCharts(data, 24, $("#timeDownStnLineCharts"));
//    			}
//    		}else{
//    			combinUnsafeTimeCharts(data, 0, $("#timeLineCharts"));
//    			
//    		}
    		combinUnsafeTimeCharts(data, 0, $("#timeLineCharts"));
    		combinUnsafeTimeCharts(data, 24, $("#timeDownStnLineCharts"));
    		
    	});
    }
    
    
    function combinUnsafeTimeCharts(data, start, obj){
    	var title = "不安全行为小时统计";
    	if(start > 0){
    		title = lineName + "下行" + title;
    	}else{
    		title = lineName + "上行" + title;
    	}
    	
    	var json = {};
    	json.name = $("#drvSctBhvType").find("option:selected").text();
    	json.data = [];
    	if(data && data.length > 0){
    		for(var i=start;i<(start+24);i++){
    			json.data.push(data[i].bhvCount);
    		}
    	}else{
    		for(var i=start;i<(start+24);i++){
    			json.data.push(0);
    		}
    	}
    	obj.highcharts({
            chart: {
                type: 'column'
            },
            title: {
                text: title
            },
            xAxis: {
                categories: [
                    '0点', '1点', '2点', '3点', '4点', '5点', '6点', '7点', '点8', '9点', '10点', '11点', '12点', 
                    '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点'
                ],
                crosshair: true
            },
            credits: {
        		enabled: false
        	},
            yAxis: {
                min: 0,
                title: {
                    text: '次'
                }
            },
            tooltip: {
                headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y:.1f} 次</b></td></tr>',
                footerFormat: '</table>',
                shared: true,
                useHTML: true
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
            series: [json]
        });
    	
    	
    	
    }
    
    

    /**
     * 标记点击显示信息
     * @param e 目标元素
     */
    function markerClick(e) {
        infoWindow.setContent(e.target.content);
        infoWindow.open(map, e.target.position);
    }

    /**
     * 设定 显示/隐藏
     * @param obj1 被点击元素
     * @param obj2 隐藏的元素
     * @param obj3 显示的元素
     */
    function showHideToggle(obj1, obj2, obj3) {
        obj1.addActiveClass();
        obj2.hide();
        obj3.show();
    }

    /**
     * 生成地图
     */
    function createMap(){
    	downCircleAreaAr = [];
    	upCircleAreaAr = [];
    	map = new AMap.Map("iCenter", {
            resizeEnable: true,
            scrollWheel: false,
            zoom: 13 
        });
        toolBar = new AMap.ToolBar({
        	ruler:true
        });
        map.addControl(toolBar);
    }
    
    /**
     * 加载页面各功能
     */
    function initPageData() {
    	persistCurrentCondition(lineId, lineName, dateType);
    	createMap();
        infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30), autoMove:false});
        loadSafeIndex();
        loadHarmfulTendency("020201", $('#faultsTendency'), '车辆故障趋势', '故障趋势');
        loadVehicleFaultsRanking();
        harmfulTypeRanking("020401", $('#faultType'), '故障百分比');
        loadHarmfulTendency("020301", $('#unsafeTendency'), '不安全行为趋势', '不安全行为趋势');
        harmfulTypeRanking("020601", $('#unsafeType'), '不安全行为百分比');
        loadUnsafeDriverRanking();
        loadLineCity();
    }
    
    /**
	 * 自动加载
	 */
	function autoLoadData(){
		var condition = getCurrentCondition();
        var _cookileLineId;
        if(condition[0]){
            _cookileLineId = condition[0];
        }
        if (condition[1]) {
            dateType = condition[1];
        }
		if(lineId){
            var treeObj = $.fn.zTree.getZTreeObj("lineTree");
            var node = treeObj.getNodeByParam("id", _cookileLineId, null);
            if (node) {
                $("#dateDiv").find('a').removeClass("active");
                $("#dateDiv").find('a[val="' + dateType + '"]').addClass("active");
                lineId = _cookileLineId;
                lineName = node.name;
                $("#showlineName").html("当前线路 : " + lineName);
                treeObj.selectNode(node);
                getFullDate();
                initPageData();
            } else {
                //载入后默认加载昨天
                $("#dateDiv").find('a:first').click();
            }
		}else{
			//载入后默认加载昨天
			$("#dateDiv").find('a:first').click();
		}
	}
	
	/**
	 * 跳转到故障统计
	 */
	toFaultSummery = function(sign, statisType){
		var data = {};
		data.statisType = 'LINE';
		data.lineId = lineId;
		data.dateType = dateType;
		data.mftGradeCode = sign;
		if(statisType && statisType != ''){
			data.statisType = statisType;
		}
		data.mftTypeCode = "";
		$.openTab('4270f3bb02fa4bf0bab5f40a351ae747', 'searchFaultSummery', [data]);
	};
	
	/**
	 * 跳转不安全行为统计
	 */
	function toUnsafeSummery(statisType){
		var data = {};
		data.lineId = lineId;
		data.dateType = dateType;
		data.statisType = statisType;
        if(statisType==='DRIVER'){
            $.openTab('0faa7a5b3279477b813cefe5a5362bd1', 'searchUnsafeSummery', [data]);
        }
        else if(statisType==='LINE'){
            $.openTab('0faa7a5b3279477b813cefe5a5362bd2', 'searchUnsafeSummery', [data]);
        }

	}

    //==============================================事件编辑
    //TODO
    //不安全行为选择
    $("#drvSctBhvType").change(function(){
    	infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30), autoMove:false});
    	createMap();
    	loadLineCity();
    });
    
    //日期点击
    $("#dateDiv").find('a').click(function () {
        $("#dateDiv").find('a').removeClass("active");
        dateType = $(this).attr("val");
        dateAr = [];
		getFullDate();
        //加载页面各项
        initPageData();
        $(this).addClass("active");
    });

    //显示/隐藏
    $("#changeVehicleRank").click(function () {
        showHideToggle($(this), $("#faultTypeDiv"), $("#vehicleTypeDiv"));
    });

    $("#changeFaultsRank").click(function () {
        showHideToggle($(this), $("#vehicleTypeDiv"), $("#faultTypeDiv"));
    });

    $("#changeUnsafeDrv").click(function () {
        showHideToggle($(this), $("#unsafeBhvDiv"), $("#unsafeDrvDiv"));
    });

    $("#changeUnsafeBhv").click(function () {
        showHideToggle($(this), $("#unsafeDrvDiv"), $("#unsafeBhvDiv"));
    });

    
    //==================================================================
    $("#changeUnsafeMap").click(function () {
//        showHideToggle($(this), $("#unsafeStnDiv"), $("#unsafeMapDiv"));
    	$(this).addActiveClass();
    	$("#unsafeStnDiv").hide();
    	$("#unsafeTimeDiv").hide();
    	$("#unsafeMapDiv").show();
        loadLineCity();
    });

    $("#changeUnsafeStn").click(function () {
//        showHideToggle($(this), $("#unsafeMapDiv"), $("#unsafeStnDiv"));
    	$(this).addActiveClass();
    	$("#unsafeMapDiv").hide();
    	$("#unsafeTimeDiv").hide();
    	$("#unsafeStnDiv").show();
    });
    
    $("#changeUnsafeTime").click(function () {
//        showHideToggle($(this), $("#unsafeMapDiv"), $("#unsafeStnDiv"));
    	$(this).addActiveClass();
    	$("#unsafeMapDiv").hide();
    	$("#unsafeStnDiv").hide();
    	$("#unsafeTimeDiv").show();
    });
    
    

    $("#changeUp").click(function () {
        showHideToggle($(this), $("#downStnLineDiv"), $("#upStnLineDiv"));
        
        showHideToggle($(this), $("#downTimeLineDiv"), $("#upTimeLineDiv"));
        //隐藏下行气泡和圆形区域
        hideInfoWinAndCircle(downInfoWin, downCircleAreaAr);
        //显示上行
        showInfoWinAndCircle(upInfoWin, upPosition, upCircleAreaAr);
    });

    $("#changeDown").click(function () {
        showHideToggle($(this), $("#upStnLineDiv"), $("#downStnLineDiv"));
        
        showHideToggle($(this), $("#upTimeLineDiv"), $("#downTimeLineDiv"));
        //隐藏上行气泡和圆形区域
        hideInfoWinAndCircle(upInfoWin, upCircleAreaAr);
        //显示下行
        showInfoWinAndCircle(downInfoWin, downPosition, downCircleAreaAr);
        
    });
    
    //--------------------------跳转部分
    $("#seriousFaultMore").click(function(){
		toFaultSummery('MFTC0002');
	});
	$("#commonFaultsMore").click(function(){
		toFaultSummery('MFTC0001');
	});
	$("#faultCarsMore, #faultsTendencyMore").click(function(){
		toFaultSummery('');
	});
	
	$("#faultRankInfoMore").click(function(){
		if($("#changeFaultsRank").attr("class") == 'item active'){
			toFaultSummery('', 'FAULT');
		}else if($("#changeVehicleRank").attr("class") == 'item active'){
			toFaultSummery('');
		}
	});
	
	$("#unsafeBhvMore, #unsafeDriversMore, #unsafeTendencyMore").click(function(){
		toUnsafeSummery('LINE');
	});
	
	$("#unsafeBhvInfoMore").click(function(){
		if($("#changeUnsafeBhv").attr("class") == 'item active'){
			toUnsafeSummery('LINE');
		}else if($("#changeUnsafeDrv").attr("class") == 'item active'){
			toUnsafeSummery('DRIVER');
		}
	});
    
    
    initElements();
    initLineTree();
    //加载
	autoLoadData();

});